/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2025-02-11 16:21:46
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-02-24 16:55:12
 * @FilePath: /vue3-admin-server/src/utils/code.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import * as crypto from 'crypto';

// 生成一个随机的 256 位（32 字节）密钥
export const generateRandomKey = () => {
    return crypto.randomBytes(32);
};

// 生成一个随机的 16 字节（128 位）初始化向量 (IV)
export const generateRandomIV = () => {
    return crypto.randomBytes(16);
};

// AES 加密函数
export const aesEncrypt = (
    text: string,
    key: Buffer<ArrayBufferLike>,
    iv: Buffer<ArrayBufferLike>
) => {
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return { ivHex: iv.toString('hex'), encryptedData: encrypted };
};

// AES 解密函数
export const aesDecrypt = (
    encrypted: string,
    key: Buffer<ArrayBufferLike>,
    ivHex: string
) => {
    const iv = Buffer.from(ivHex, 'hex');
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    let decrypted = decipher.update(encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
};
